package com.example.content_android;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.youth.banner.Banner;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;


import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.RequestBody;

public class LoginActivity extends AppCompatActivity {
    private EditText accountText = null;
    private EditText passwordTest = null;
    private SharedPreferences sp;

    private CheckBox remember=null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //隐藏界面默认标题栏
        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.hide();
        }

        //设置顶部状态栏黑底白字（最上面这一行显示电池、时钟、wifi等图标是状态栏）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(Color.BLACK);
        }

        setContentView(R.layout.activity_login);
        accountText = findViewById(R.id.account);
        passwordTest = findViewById(R.id.password);
        remember=findViewById(R.id.remember);
        sp=getSharedPreferences("userInfo",MODE_PRIVATE);//将内容存放到名为userInfo的文档内
        if(sp.contains("remember")&&sp.getBoolean("remember",true)){

            String userName=sp.getString("userName","");
            String password=sp.getString("password","");
            accountText.setText(userName);
            passwordTest.setText(password);
            remember.setChecked(true);
        }

    }

    public void login(View v) {
        String account = accountText.getText().toString();
        String password = passwordTest.getText().toString();


        if (TextUtils.isEmpty(account))//判断内容是否为空
        {
            Toast.makeText(this, "账号为空！", Toast.LENGTH_SHORT).show();

            return;
        }
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码为空！", Toast.LENGTH_SHORT).show();

            return;
        }
        String url = "https://www.turkeylike.cn:8900/fzulab/sys/mLogin";
        MediaType JSONType = MediaType.parse("application/json; charset=utf-8");
        JSONObject json = new JSONObject();
        try {
            json.put("userName", account);
            json.put("password", password);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        OkHttpUtils
                .postString()
                .url(url)
                .content(json.toString())
                .mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(
                new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("onResponse", "response");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        JSONObject responseStr = JSON.parseObject(response);
                        if( responseStr.getInteger("code")==500){
                          String msg=responseStr.getString("msg");

                            Toast.makeText(getBaseContext(),msg,Toast.LENGTH_SHORT).show();
                                return;

                        }
                        sp=getSharedPreferences("userInfo",MODE_PRIVATE);//将内容存放到名为userInfo的文档内
                        SharedPreferences.Editor editor = sp.edit();
                       if( responseStr.getInteger("code")==0){
                           // com.alibaba.fastjson.JSONObject
                           for (Map.Entry<String, Object> entry : responseStr.getJSONObject("result").entrySet()) {
                               String key = entry.getKey();
                               Object value = entry.getValue();
                               if("token".equals(key)){
                                   editor.putString("token", value.toString());
                               }
                           }

//获得SharedPreferences对象




                           editor.putString("userName", accountText.getText().toString());

                           editor.putString("password", passwordTest.getText().toString());
                           editor.putBoolean("isVisitor",false);
                           if(remember.isChecked()){
                               editor.putBoolean("remember",true);
                           }else{
                               editor.remove("remember");
                           }


                           editor.commit();
                           Intent intent = new Intent(LoginActivity.this, MainActivity.class);

                           intent.putExtra("id", 1);

                           startActivity(intent);
                       }





//                        if (bannerArray != null && bannerArray.size() > 0) {
//                            for (int i = 0; i < bannerArray.size(); i++) {
//                                JSONObject str = JSON.parseObject(bannerArray.get(i).toString());
//
//
//                            }
//                        }

                        Log.e("onResponse", "response");
                    }
                }
        );

//        RequestBody requestBody = RequestBody.create(JSONType, String.valueOf(json));
//
//
//        OkHttpUtils.post().url(url).params(params).build().execute(new StringCallback() {
//            @Override
//            public void onError(Call call, Exception e, int id) {
//                Log.e("onResponse", "response");
//            }
//
//            @Override
//            public void onResponse(String response, int id) {
//                JSONObject responseStr = JSON.parseObject(response);
//
//                Map<String, String> map2 = JSON.parseObject(response, Map.class);
//
//                JSONArray bannerArray = responseStr.getJSONArray("result");
//                if (bannerArray != null && bannerArray.size() > 0) {
//                    for (int i = 0; i < bannerArray.size(); i++) {
//                        JSONObject str = JSON.parseObject(bannerArray.get(i).toString());
//
//
//                    }
//                }
//
//                Log.e("onResponse", "response");
//            }
//        });

//        if(n.equals(name) && p.equals(password))//判断获取的是否和设置的一样
//        {
//            Intent intent = new Intent(this,MainActivity2.class);
//
//            intent.putExtra("Data",n);
//
//            startActivity(intent);
//            //2.uri跳转
//            //        Uri uri= Uri.parse("tel:10086");
//            //        Intent intent = new Intent(Intent.ACTION_DIAL,uri);
//            //
//            //        startActivity(intent);
//
//            return;
//        }

//        Toast.makeText(this, "账号或密码输入有误", Toast.LENGTH_SHORT).show();


    }

//    private void login(){OkHttpClient client = HttpUtils.getClient();
//    String userName = userNameEdit.getText().toString();
//    String userPwd = userPwdEdit.getText().toString();
//    String captcha = verifyCodeEdit.getText().toString();
//    if (userName.equals("")) {showMsg("用户名不能为空");return;}if (userPwd.equals("")) {showMsg("密码不能为空");return;}
//    if (captcha.equals("")) {showMsg("验证码不能为空");return;}
//    MediaType JSON = MediaType.parse("application/json; charset=utf-8");
//    JSONObject json = new JSONObject();
//    try {json.put("userName", userName);json.put("userPwd", userPwd);json.put("captcha", captcha);} catch (JSONException e) {e.printStackTrace();}
//    RequestBody requestBody = RequestBody.create(JSON, String.valueOf(json));
////        RequestBody formBody = new FormBody.Builder()
////                .add("userName", userName)
////                .add("userPwd", userPwd)
////                .add("verifyCode", captcha)
////                .build();
////                final Request request = new Request.Builder().url(AppConfig.LOGIN_URL).post(requestBody).build();
////                Call call = client.newCall(request);
////                call.enqueue(new Callback()
////                {@Overridepublic void onFailure(Call call, IOException e) {//此处涉及到ui操作，只能在主线程中操作uirunOnUiThread(new Runnable() {@Overridepublic void run() {showMsg("请求服务器失败");}});}@Overridepublic void onResponse(Call call, Response response) throws IOException {runOnUiThread(new Runnable() {@Overridepublic void run() {try {Result result;result = JSONObject.parseObject(response.body().string(),Result.class);if(result.getCode() == 200){showMsg("登录成功");Intent intent = new Intent(LoginActivity.this,MainActivity.class);startActivity(intent);finish();}else{showMsg(result.getMsg());}} catch (IOException e) {e.printStackTrace();}}});}});}

}
